package com.example.administrator.myapplication;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.Layout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.TextView;
import net.xxhong.rosclient.R;
import java.math.BigDecimal;
public class CustomTakeValueArticle extends View {
    private final int COLOR_PROFIT_LINE = getResources().getColor(R.color.scroll_bar_line_red);
    private final int COLOR_PROFIT_TEXT = getResources().getColor(R.color.scroll_bar_text_red_label);
    private final int COLOR_LOSS_LINE = getResources().getColor(R.color.scroll_bar_line_bule);
    private final int COLOR_LOSS_TEXT = getResources().getColor(R.color.scroll_bar_text_bule_label);
    private Bitmap mCursorBmp;
    private Bitmap mTrunkBmp;
    private Matrix matrix;
    private Bitmap dstbmp;
    private Matrix matrixDeep;
    private Bitmap mTrunkBmpDeep;
    private Paint mPaint;
    private float mCursorTextSize = 0;
    private float mTrunkMarginTop = 20;
    private double mXAxisStart;
    private double mXAxisEnd;
    private double mScaling;
    private float mCursorWidth = 0;
    private int mCursorHight = 0;
    private int mTrunkHight = 0;
    private float TRUNKMARGINTOP = 15;
    private boolean ISCENTERVERTICALTRUNK = true;
    private double x = 0;
    private int mTextCursorSpace = 0;
    private final float TEXT_CURSOR_SPACE = 0.5f;
    private int TEXTSIZE = 10;
    private float mTextHight;
    private boolean isProfit = true;
    private OnScrollListener onScrollListener;
    private OnClickListener onClickListener;
    private boolean noSetX = true;
    private float mLineWidth = 0;
    private final int LINEWIDTH = 1;
    private double value;
    private String scrollValue = "0";
    private int mTouchSlop = 0;
    private int mClickTimeout = 0;
    private int precision;
    private Boolean isInteger=true;
    public CustomTakeValueArticle(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }
    public CustomTakeValueArticle(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    private void init(Context context) {
        mTrunkBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.cursor_line_red);
        mTrunkBmpDeep = BitmapFactory.decodeResource(getResources(), R.mipmap.cursor_line_red_deep);
        mCursorBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.red_cursor);
        matrix = new Matrix();
        matrixDeep = new Matrix();
        mTrunkHight = mTrunkBmp.getHeight();
        mCursorWidth = mCursorBmp.getWidth();
        mCursorHight = mCursorBmp.getHeight();
        mTrunkMarginTop = dip2px(context, TRUNKMARGINTOP);
        mTextCursorSpace = dip2px(context, TEXT_CURSOR_SPACE);
        mCursorTextSize = sp2px(context, TEXTSIZE);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mClickTimeout = ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout();
        mLineWidth = dip2px(context, LINEWIDTH);
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setTextSize(mCursorTextSize);
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        mTextHight = (int) (fontMetrics.descent - fontMetrics.ascent + 0.5f);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mScaling = (getWidth() - getPaddingRight() - getPaddingLeft() - mCursorWidth)
                / (getXAxisEnd() - getXAxisStart());
        if (ISCENTERVERTICALTRUNK) {
            mTrunkMarginTop = (getHeight() - mTrunkHight) / 2.0f;
        }
        if (dstbmp != null)
            dstbmp.recycle();
        dstbmp = null;
        drawTrunk(canvas, mTrunkMarginTop);
        drawCursor(canvas);
    }
    private void drawTrunk(Canvas canvas, float mTrunkMarginTop) {
        int leftbmp = getPaddingLeft();
        int topBoundary = (int) (mTrunkMarginTop + 0.5f);
        int widthbmp = getWidth() - getPaddingLeft() - getPaddingRight();
        float scaw = widthbmp * 1.0f / (mTrunkBmp.getWidth());
        matrix.setScale(scaw, 1.0f);
        if (dstbmp == null)
            dstbmp = Bitmap.createBitmap(mTrunkBmp, 0, 0, mTrunkBmp.getWidth(), mTrunkBmp.getHeight(), matrix, true);
        canvas.drawBitmap(dstbmp, leftbmp, topBoundary, null);
        if (x - mXAxisStart >= 0 && mXAxisEnd - x >= 0) {
            scaw = (float) (getWidthForXValue() * 1.0f / mTrunkBmpDeep.getWidth());
        } else if (mXAxisEnd - x < 0) {
            scaw = (float) (getWidthForXValue() * 1.0f / mTrunkBmpDeep.getWidth());
        } else {
            scaw = mCursorWidth / 2.0f / mTrunkBmpDeep.getWidth();
        }
        float scaH = mTrunkBmp.getHeight() * 1.0f / mTrunkBmpDeep.getHeight();
        matrixDeep.setScale(scaw, scaH);
        Bitmap dstbmpdeep = Bitmap.createBitmap(mTrunkBmpDeep, 0, 0, mTrunkBmpDeep.getWidth(),
                mTrunkBmpDeep.getHeight(), matrixDeep, true);
        canvas.drawBitmap(dstbmpdeep, leftbmp, topBoundary, null);
        double tempX = getXForXvalue(mXAxisEnd);
        mPaint.setColor(getTrunkTextColor());
        String mEnd;
        if (isInteger) {
            mEnd = String.valueOf((int) mXAxisEnd);
        } else {
            BigDecimal bd = new BigDecimal(mXAxisEnd);
            bd = bd.setScale(precision, BigDecimal.ROUND_HALF_DOWN);
            mEnd = String.valueOf(bd.doubleValue());
        }
        refitText(mEnd, computeMaxStringWidth(mEnd));
        canvas.drawText(mEnd, (float) tempX,
                mTrunkHight / 2.0f + mCursorHight + mTextHight + mTextHight / 2.0f,
                mPaint);
        String mStart;
        if (isInteger) {
            mStart = String.valueOf((int) mXAxisStart);
        } else {
            BigDecimal bd = new BigDecimal(mXAxisStart);
            bd = bd.setScale(precision, BigDecimal.ROUND_HALF_UP);
            mStart = String.valueOf(bd.doubleValue());
        }
        double tempSX = getXForXvalue(mXAxisStart);
        mPaint.setColor(getTrunkTextColor());
        refitText(mStart, computeMaxStringWidth(mStart));
        canvas.drawText(mStart, (float) tempSX,
                mTrunkHight / 2.0f + mCursorHight + mTextHight + mTextHight / 2.0f,
                mPaint);
        float lineW = (mLineWidth + 0.5f);
        float tempLSX = (float) getXForXvalue(mXAxisStart);
        mPaint.setColor(getTrunkTextColor());
        canvas.drawRect(tempLSX, mTrunkMarginTop, tempLSX + lineW, mTrunkMarginTop + mTrunkHight, mPaint);
        float tempLEX = (float) getXForXvalue(mXAxisEnd);
        mPaint.setColor(getTrunkTextColor());
        canvas.drawRect(tempLEX, mTrunkMarginTop, tempLEX + lineW, mTrunkMarginTop + mTrunkHight, mPaint);
    }
    private void drawCursor(Canvas canvas) {
        canvas.drawBitmap(mCursorBmp, (int) (getXLocation() - mCursorWidth / 2.0f + 0.5f),
                (int) (mTrunkMarginTop + mTrunkHight / 2.0f - mCursorHight / 2.0f + 0.5f), null);
        if (isInteger) {
            scrollValue = String.valueOf(((int) value));
        } else {
            BigDecimal bd = new BigDecimal(scrollValue);
            bd = bd.setScale(precision, BigDecimal.ROUND_HALF_UP);
            scrollValue = String.valueOf(bd.doubleValue());
        }
        mPaint.setColor(getCursorTextColor());
        refitText(scrollValue, computeMaxStringWidth(scrollValue));
        canvas.drawText(scrollValue, (int) (getXLocation() + 0.5f),
                (int) (mTrunkMarginTop - mCursorHight / 2.0f + mTrunkHight / 2.0f + 0.5f - mTextCursorSpace),
                mPaint);

    }
    public void setCursorBmp(Bitmap mCursorBitmap) {
        this.mCursorBmp = mCursorBitmap;

    }
    public void setTrunkBmp(Bitmap mTrunkBitmap) {
        this.mTrunkBmp = mTrunkBitmap;
    }
    public void setTrunkBmpDeep(Bitmap mTrunkBitmapDeep) {
        this.mTrunkBmpDeep = mTrunkBitmapDeep;
    }
    public void setIsProfit(boolean isProfit) {
        this.isProfit = isProfit;
    }
    public int getCursorTextColor() {
        return isProfit ? COLOR_PROFIT_TEXT : COLOR_LOSS_TEXT;
    }
    public int getTrunkTextColor() {
        return isProfit ? COLOR_PROFIT_LINE : COLOR_LOSS_LINE;
    }
    public double getXAxisEnd() {
        return mXAxisEnd;
    }
    public double getXAxisStart() {
        return mXAxisStart;
    }
    public void setValueScale(double mXAxisStart, double mXAxisEnd) {
        this.mXAxisStart = mXAxisStart;
        this.mXAxisEnd = mXAxisEnd;
    }
    public void setXValue(double x) {
        if (mXAxisStart != 0 || mXAxisEnd != 1)
            noSetX = false;
        this.x = x;
        this.scrollValue = String.valueOf(x);
        this.value = x;
    }
    public void setOnScrollListener(OnScrollListener onScrollListener) {
        this.onScrollListener = onScrollListener;
    }
    private double getXValueForPx(double xpx) {
        double d = (xpx - getPaddingLeft() - mCursorWidth / 2.0f) / mScaling + mXAxisStart;
        return d;
    }

    private double getXForXvalue(double xvalue) {
        int x = getPaddingLeft() + (int) ((xvalue - mXAxisStart) * mScaling + mCursorWidth / 2.0f + 0.5f);
        return x;
    }
    private int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    private int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
    public double getXLocation() {
        Paint.Align align = Paint.Align.LEFT;
        double px = getXForXvalue(x);
        if (noSetX) {
            px = align == Paint.Align.LEFT ? 0 : getWidth();
        }
        if (px <= getPaddingLeft() + mCursorWidth / 2.0f)
            px = getPaddingLeft() + mCursorWidth / 2.0f;
        if (px >= getWidth() - getPaddingRight() - mCursorWidth / 2.0f)
            px = getWidth() - getPaddingRight() - mCursorWidth / 2.0f;
        return px;
    }
    public void setXLocation(double x) {
        setXValue(getXValueForPx(x));
    }
    public float getTextSize() {
        return mCursorTextSize;
    }
    public interface OnScrollListener {
        String onScroll(double x);
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public interface OnClickListener {
        String onClick(double x);
        String onClick_up(double x);
    }

    private double getWidthForXValue() {
        double strat = getXForXvalue(x);
        return strat != 0 && strat > 0 ? strat : 1;
    }

    float startX = 0;
    float startY = 0;
    boolean isClick = true;

    @SuppressLint("ClickableViewAccessibility")
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                getParent().requestDisallowInterceptTouchEvent(true);
                if ((Math.abs(event.getX() - x) <= mCursorWidth) && (getXValueForPx(event.getX()) <= mXAxisEnd &&
                        getXValueForPx(event.getX()) >= mXAxisStart)) {
                    setXLocation(event.getX());
                }
                startX = event.getRawX();
                startY = event.getRawY();
                isClick = true;
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = event.getRawX() - startX;
                float dy = event.getRawY() - startY;
                if (onScrollListener != null) {
                    setXLocation(event.getX());
                    this.scrollValue = onScrollListener.onScroll(getXValueForPx(getXLocation()));
                    this.value = getXValueForPx(getXLocation());
                } else if (Math.abs(dx) > mTouchSlop || Math.abs(dy) > mTouchSlop) {
                    isClick = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                double tempX = getXForXvalue(getXLocation());
                if (Math.abs(getXLocation() - tempX) <= mCursorWidth && (getXValueForPx(event.getX()) <= mXAxisEnd &&
                        getXValueForPx(event.getX()) >= mXAxisStart)) {
                    setXLocation(tempX);
                } else if (isClick && event.getEventTime() - event.getDownTime() < mClickTimeout) {
                    //作为点击事件操作
                    if (onClickListener != null) {
                        setXLocation(event.getX());
                        this.scrollValue = onClickListener.onClick(getXValueForPx(getXLocation()));
                        this.value = getXValueForPx(getXLocation());
                    }
                }
                onClickListener.onClick_up(x);
                break;
        }
        invalidate();
        return true;
    }
    public double getValue() {
        return this.value;
    }
    public double getMaxValue() {
        return this.mXAxisEnd;
    }
    public double getMinValue() {
        return this.mXAxisStart;
    }
    public void setPrecision(int precision) {
        this.precision = precision;
    }
    public void setType(Boolean isInteger) {
        this.isInteger = isInteger;
    }
    private int computeMaxStringWidth(String strings) {
        TextView textView = new TextView(getContext());
        textView.setText(strings);
        TextPaint paint = textView.getPaint();
        int widthText = (int) Layout.getDesiredWidth(strings, 0,
                strings.length(), paint);
        return widthText;
    }
    private void refitText(String text, int textWidth) {
        if (textWidth > 0) {
            float[] widths = new float[text.length()];
            Rect rect = new Rect();
            mPaint.getTextBounds(text, 0, text.length(), rect);
            int textWidths = rect.width();
            mCursorTextSize = this.getTextSize();
            while (textWidths > 48) {
                mCursorTextSize = mCursorTextSize - 1;
                mPaint.setTextSize(mCursorTextSize);
                textWidths = mPaint.getTextWidths(text, widths);
            }
            mPaint.setTextSize(mCursorTextSize);
        }
        invalidate();
    }
}
